package com.bookseek.xreader.views.fragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bookseek.xreader.R;
import com.bookseek.xreader.params.GujiSearchParams;
import com.bookseek.xreader.utils.DLog;
import com.bookseek.xreader.utils.JkhlUtils;
import com.bookseek.xreader.utils.MiniDataUtils;
import com.bookseek.xreader.utils.OkHttpUtils;
import com.bookseek.xreader.vo.GujiItemVo;
import com.bookseek.xreader.vo.PageResult;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;


public class GujiFragment extends BaseFragment {


    private View rootView;
    private RecyclerView recyclerView;
    private GujiAdpter gujiAdpter;
    private Integer PAGE_SIZE = 10;
    private Integer CUR_PAGE = 1;
    public List<GujiItemVo> datas = new ArrayList<>();
    public Integer count;
    private GujiSearchParams params = new GujiSearchParams();
    private LinearLayoutManager layoutManager;
    private boolean isLoading = false;
    public void transData(PageResult<GujiItemVo> pageVo){
        List<GujiItemVo> datas = pageVo.datas;
        if(datas == null || datas.size() == 0){
            return;
        }
        Map<String, String> MP = new HashMap<>();
        MP.put(":A:", "mockapi.eolink.com");
        MP.put(":B:", "note.youdao.com");
        MP.put(":C:", "fastly.jsdelivr.net");
        MP.put(":D:", "cdn.jsdelivr.net");
        MP.put(":E:", "gcore.jsdelivr.net");
        Map<String,String> hm = pageVo.hm;
        for(GujiItemVo itemVo : datas){
            List<String> newCvs = new ArrayList<>();
            if(!JkhlUtils.toStr(itemVo.coverUrl).startsWith("http")){
                itemVo.coverUrl = "https://" + hm.get(itemVo.h) + itemVo.c;
            }
        }
    }
    public void loadData(){
        params.pageSize = PAGE_SIZE;
        params.page = CUR_PAGE;
        String w = OkHttpUtils.gujiW(params);
        String api = OkHttpUtils.gujiApi("/toktok/filep?w="+w);
        Long aTm = System.currentTimeMillis();
        OkHttpUtils.getInstance().get(api, new OkHttpUtils.SimpleCallback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Long bTm = System.currentTimeMillis();
                if(response.isSuccessful()){
                    String text = response.body().string();
                    String jsonText = MiniDataUtils.aesDecryptCBCWithIvFromBase64SafeUrlJSONP(text);
                    Long cTm = System.currentTimeMillis();
                    Log.i(TAG,"bTm-aTm="+(bTm-aTm)+" cTm - bTm = "+(cTm-bTm));
                    PageResult<GujiItemVo> pageVo = OkHttpUtils.gson.fromJson(jsonText,new TypeToken<PageResult<GujiItemVo>>(){}.getType());
                    transData(pageVo);
                    count = pageVo.count;
                    datas.addAll(pageVo.datas);
                    Log.i(TAG,"count="+pageVo.count);
                    if(getActivity() != null){
                        getActivity().runOnUiThread(()->{
                            gujiAdpter.notifyDataSetChanged();
                            isLoading = false;
                        });
                    }

                }
            }
        });
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.i(TAG,"GujiFragment.onCreateView");
        rootView = inflater.inflate(R.layout.fragment_guji, container, false);
        recyclerView = rootView.findViewById(R.id.gujiIndexRecyclerView);
        layoutManager = new LinearLayoutManager(baseContext,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
        gujiAdpter = new GujiAdpter();
        recyclerView.setAdapter(gujiAdpter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if (!isLoading && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0) {
                    isLoading = true;
                    CUR_PAGE++;
                    loadData();
                }
            }
        });

        loadData();
        return  rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DLog.info("GujiFragment.onDestroy====>");
    }

    class GujiAdpter extends RecyclerView.Adapter<GujiAdpter.GujiHolder>{
        @NonNull
        @Override
        public GujiHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(baseContext).inflate(R.layout.guji_list_item,parent,false);
            GujiHolder  gujiHolder = new GujiHolder(view);
            Log.i(TAG,"---init--GujiHolder parent.getContext()=baseContext"+(parent.getContext() == baseContext));
            return gujiHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull GujiHolder holder, int position) {
            GujiItemVo itemVo = datas.get(position);
            holder.gnameTv.setText(JkhlUtils.toStr(itemVo.t));
            holder.labelTv.setText("label-"+position);
            Log.i(TAG,"onBindViewHolder--"+position);
            if(!JkhlUtils.isBlank(itemVo.coverUrl)){
                Glide.with(GujiFragment.this).load(itemVo.coverUrl)
                        .into(holder.coverImage);
            }
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        class GujiHolder extends RecyclerView.ViewHolder {
            ImageView coverImage;
            TextView gnameTv;
            TextView labelTv;
            public GujiHolder(@NonNull View itemView) {
                super(itemView);
                gnameTv = itemView.findViewById(R.id.gnameTv);
                labelTv = itemView.findViewById(R.id.labelTv);
                coverImage = itemView.findViewById(R.id.coverImage);
            }
        }
    }

}